package org.funtester.performance.books.chapter01.section4;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadFactoryDemo {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 5, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactory() {// 创建线程池

            AtomicInteger index = new AtomicInteger(1);// 线程索引

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);// 创建线程
                thread.setName("FunTester-" + index.getAndIncrement());// 设置线程名称
                return thread;
            }
        });
        for (int i = 0; i < 3; i++) {
            executor.execute(() -> {// 提交任务
                try {
                    Thread.sleep(1000);// 休眠1秒,模拟任务执行时间
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + " is running");// 输出线程名称
            });
        }
        executor.shutdown();// 关闭线程池
    }

}
